#include "CompletionsDialog.h"
#include <QGridLayout>
#include <QFileDialog>
#include <QFile>
#include "common.h"


//-------------------------------------

CompletionsDialog::CompletionsDialog(QWidget *parent) :
    QDialog(parent)
{
    buttonBox = new QDialogButtonBox( this );
    buttonBox->setOrientation(Qt::Horizontal);
    buttonBox->setStandardButtons( QDialogButtonBox::Cancel | QDialogButtonBox::Ok );
    teTreeCompletions = new QTextEdit( this );
    teTreeCompletions->setTabStopWidth( 20 );

    QGridLayout *layout = new QGridLayout;
    layout->addWidget( teTreeCompletions, 0, 0 );
    layout->addWidget( buttonBox, 1, 0 );

    connect( buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect( buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    setLayout( layout );
    resize( 800, 600 );
    loadKeyTree();
}

//-------------------------------------

CompletionsDialog::~CompletionsDialog()
{
}

//-------------------------------------

void CompletionsDialog::accept()
{
     saveKeyTree();
     QDialog::accept();
}

//-------------------------------------

void CompletionsDialog::loadKeyTree()
{
    QString fileName = KEYS_TREE_FILE_NAME;

    if( fileName.isNull() )
        fileName = QFileDialog::getOpenFileName( this, "Open File", "", "Keys Tree Files ( *.conf )" );

    if( !fileName.isEmpty() )
    {
        QFile file( fileName );
        if( file.open( QFile::ReadOnly | QFile::Text ) )
        {
            teTreeCompletions->setPlainText( file.readAll() );
            file.close();
        }
    }
}

//-------------------------------------

void CompletionsDialog::saveKeyTree()
{
    QString f = KEYS_TREE_FILE_NAME;

    if( f.isNull() )
        f = QFileDialog::getSaveFileName( this, "Save as ...", "", "Keys Tree Files ( *.conf )");

    if( !f.isEmpty() )
    {
        QFile ff( f );
        if( ff.open( QFile::WriteOnly | QFile::Text ) )
        {
            ff.write( teTreeCompletions->toPlainText().toAscii() );
            ff.close();
        }
    }
}

//-------------------------------------


